package io.gitee.icefairy.total_monitor.Interceptor

import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * AUTHOR:icefairy
 * DATE:2021/12/23 0023 11:06
 **/
@Configuration
open class CommonInterceptor : WebMvcConfigurer {
    @Value("\${tm.key}")
    var HEADER_KEY = "tmkey"

    @Value("\${tm.secret}")
    val HEADER_VAL = ""
    override fun addInterceptors(registry: InterceptorRegistry) {
        super.addInterceptors(registry)
        registry.addInterceptor(object : HandlerInterceptor {
            override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
                val gotValue = request.getHeader(HEADER_KEY) ?: ""
                if (gotValue.compareTo(HEADER_VAL) != 0) {
                    response.writer.println("error access")
                    return false
                } else {
                    return true
                }
            }
        }).addPathPatterns("/monitor/active")
    }

}